package com.xidian.zhiancloud.controller.workTicket;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xidian.zhiancloud.controller.base.BaseController;
import com.xidian.zhiancloud.dto.ResultDTO;
import com.xidian.zhiancloud.dto.workTicket.FireTicketVODTO;
import com.xidian.zhiancloud.enums.GeneralResponseEnums;
import com.xidian.zhiancloud.model.SysJob;
import com.xidian.zhiancloud.model.workTicket.FireTicket;
import com.xidian.zhiancloud.qo.workTicket.FireTicketQO;
import com.xidian.zhiancloud.service.workTicket.FireFlowService;
import com.xidian.zhiancloud.service.workTicket.FireService;
import com.xidian.zhiancloud.util.zyf.RedisUtil;
import com.xidian.zhiancloud.vo.workTicket.FireTicketVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("Fire")
public class FireController extends BaseController {
    @Autowired
    private FireService fireService;

    @Autowired
    private FireFlowService fireFlowService;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 编辑
     *
     * @param fireTicket
     * @return 是否提交成功
     */
    @PostMapping("/addFireTicket")
    public ResultDTO<Boolean> addFireTicket(FireTicket fireTicket) {
        fireTicket.setCompanyId(getSessionUserCompanyId());
        fireTicket.setApplicantId(getSessionUserid());
        fireTicket.setCreateTime(new Date(System.currentTimeMillis()));
        Boolean res = true;
        // 通过是否传入id，判断是否是第一次传入（save），还是继续编辑（update）
        if (fireTicket.getId() == null) {
            res = fireService.save(fireTicket);
        } else {
            res = fireService.updateById(fireTicket);
        }
        return ResultDTO.successOf(res, GeneralResponseEnums.SUCCESS);
    }

    /**
     * 发布
     *
     * @param id
     * @return
     */
    @PostMapping("/commitFireTicket")
    public ResultDTO<Boolean> commitFireTicket(@RequestParam("id") Long id) {
        FireTicket fireTicket = fireService.getById(id);
        // 设置危险作业票id
        fireTicket.setWorkNumber(redisUtil.generateWorkId(getSessionUserCompanyId(), fireTicket.getApplicantUnitId()));
        fireTicket.setIsCommit1(1);
        // 设置导出类型
        if (fireTicket.getWorkLevel() == 0) {           // 特级
            fireTicket.setExportType(12);
        } else if (fireTicket.getWorkLevel() == 1) {    // 一级
            fireTicket.setExportType(0);
        } else if (fireTicket.getWorkLevel() == 2) {    // 二级
            fireTicket.setExportType(4);
        }
        fireTicket.setCurrentStep(2);
        fireTicket.setUpdateTime(new Date(System.currentTimeMillis()));
        Boolean res = fireService.updateById(fireTicket);
        return ResultDTO.successOf(res, GeneralResponseEnums.SUCCESS);
    }

    /**
     * 删除待提交作业票
     *
     * @param ids
     * @return
     */
    @PostMapping("/deleteFireTicket")
    public ResultDTO<Boolean> deleteFireTicket(@RequestParam("ids") Long[] ids) {
        if (ids == null) {
            return ResultDTO.errorOf(GeneralResponseEnums.REQUEST_ERROR);
        }
        Boolean res = fireService.removeByIds(Arrays.asList(ids));
        return ResultDTO.successOf(res, GeneralResponseEnums.SUCCESS);
    }

    /**
     * 各单位审批（修改）
     *
     * @param fireTicket
     * @return
     */
    @PostMapping("/approveFireTicket")
    public ResultDTO<Boolean> approveFireTicket(FireTicket fireTicket) {
        Long ticketId = fireTicket.getId();
        // 前端的fireTicket在根据id更新后端的记录时，不对以下字段做修改
        fireTicket.setUpdateTime(new Date(System.currentTimeMillis()));
        fireTicket.setCompanyId(null);
        fireTicket.setCreateTime(null);
        fireTicket.setIsCommit1(null);
        fireTicket.setIsCommit2(null);
        fireTicket.setIsCommit3(null);
        fireTicket.setIsCommit4(null);
        fireTicket.setIsCommit5(null);
        fireTicket.setIsCommit6(null);
        fireTicket.setIsCommit7(null);
        fireTicket.setIsCommit8(null);
        fireTicket.setIsCommit9(null);
        fireTicket.setIsCommit10(null);
        fireTicket.setIsCommit11(null);
        fireTicket.setIsCommit12(null);
        fireTicket.setIsCommit13(null);
        fireTicket.setIsCommit14(null);
        fireTicket.setIsCommit15(null);
        fireTicket.setIsCommit16(null);
        // 根据id查询数据库已有数据
        FireTicket fireTicketData = fireService.getById(ticketId);
        Integer currentStep = fireTicketData.getCurrentStep();

        //  判断是哪一个小步骤完成了提交
        if ((fireTicket.getFireAnalyse2Data() != null || fireTicket.getFireAnalyse3Data() != null) && fireTicketData.getFireAnalyse1Data() != null) {           // 动火分析2、3，不影响步骤判断
            ;
        } else {
            Integer subStep = fireFlowService.getFinishSubId(currentStep, fireTicket);
            // 将该小步骤步中的isCommit**设置为1，并填充时间
            fireService.setSubStepFinish(subStep, fireTicket);
        }

        Boolean res1 = false;
        // 其他编制措施提交冲突判定
        if (fireTicket.getOtherMeasure() != null) {
            return ResultDTO.errorOf(GeneralResponseEnums.ADD_FAILED);
        } else {
            // 保存提交
            res1 = fireService.updateById(fireTicket);
        }
        // 获取保存后的ticket
        FireTicket newFireTicket = fireService.getById(ticketId);
        // 判断本阶段作业流是否已经结束
        Integer updateStep = fireFlowService.updateCurrentStep(currentStep, newFireTicket);
        // 更新当前大步骤的状态
        newFireTicket.setCurrentStep(updateStep);
        Boolean res = fireService.updateById(newFireTicket);
        return ResultDTO.successOf(res || res1, GeneralResponseEnums.SUCCESS);
    }


    /**
     * 根据id查询作业票
     *
     * @param id
     * @return
     */
    @GetMapping("/getFireWorkTicket")
    public ResultDTO<FireTicketVODTO> getFireWorkTicket(@RequestParam("id") Long id) {
        if (id == null) {
            return ResultDTO.errorOf(GeneralResponseEnums.REQUEST_ERROR);
        }
        Long companyId = getSessionUserCompanyId();
        // 返回DTO对象，为fireTicketVO及操作权限标识Map
        FireTicketVODTO fireTicketVODTO = fireService.getFireTicketVODTOById(companyId, id);
        return ResultDTO.successOf(fireTicketVODTO, GeneralResponseEnums.SUCCESS);
    }

    /**
     * 根据作业票编号查询作业票id（多类型通用）
     * @param relateWorkNum
     * @return
     */
    @PostMapping("/getRelateTicketByWorkNumber")
    public ResultDTO<Map<String, Long>> getRelateTicketByWorkNumber(@RequestParam("relateWorkNum") String relateWorkNum) {
        Long companyId = getSessionUserCompanyId();
        Map<String, Long> relateWorkNumberList = new HashMap<>();

        Long relateId = fireService.getRelateTicket(relateWorkNum, companyId);
        if (relateId == null) {
            return ResultDTO.errorOf(GeneralResponseEnums.GET_FAILED);
        }
        relateWorkNumberList.put(relateWorkNum, relateId);
        return ResultDTO.successOf(relateWorkNumberList, GeneralResponseEnums.SUCCESS);
    }

    /**
     * 列表查找
     *
     * @param fireTicketQO
     * @return
     */
    @GetMapping("getFireWorkTicketList")
    public ResultDTO<IPage<FireTicketVO>> getFireWorkTicketList(FireTicketQO fireTicketQO) {
        if (fireTicketQO.getSize() == null || fireTicketQO.getCurrent() == null) {
            return ResultDTO.errorOf(GeneralResponseEnums.REQUEST_ERROR);
        }
        fireTicketQO.setCompanyId(getSessionUserCompanyId());
        return ResultDTO.successOf(fireService.getListByQO(fireTicketQO), GeneralResponseEnums.SUCCESS);
    }




}
